import i18n from 'i18next';
import {initReactI18next} from 'react-i18next';
import StorageUtils from '@/utils/storageUtils';
import enTranslation from './en.js';
import zhTranslation from './zh.js';
import vieTranslation from './vie.js';
import store from '@/store';
import {getAppLocaleList} from '@/apis/api';
const localLang = StorageUtils.getItem('APP_LANG');
import {handleSetLangList, handleSetLang} from '@/store/action/lang';

const getInitLang = async () => {
  const res = await getAppLocaleList();
  const languageGroups = res?.data || [];
  let initLang = '';
  store.dispatch(handleSetLangList(languageGroups));
  const localLang = await StorageUtils.getItem('APP_LANG');
  if (localLang) {
    const localExist = languageGroups.find(item => item.langType === localLang);
    if (localExist) {
      initLang = localLang;
      store.dispatch(handleSetLang(initLang));
      return initLang;
    }
  }

  const defaultLanguage = languageGroups.find(item => item.state === 1);
  initLang = defaultLanguage?.langType ? defaultLanguage.langType : 'zh';
  store.dispatch(handleSetLang(initLang));
  return initLang;
};
i18n
  .use(initReactI18next) // 将i18next与react-i18next绑定
  .init({
    debug: true,
    fallbackLng: 'zh',
    // supportedLngs: ['en', 'zh'],
    lng: 'zh',
    resources: {
      en: {
        translation: enTranslation,
      },
      zh: {
        translation: zhTranslation,
      },
      vie: {
        translation: vieTranslation,
      },
    },
    interpolation: {
      escapeValue: false, // 不要自动转义值
    },
  });

// 定义初始化函数
const initI18n = async () => {
  const lang = await getInitLang();
  i18n.changeLanguage(lang);
};

export {i18n, initI18n};
